package com.vlin.api.client.defaut;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import com.vlin.api.builder.client.HttpClientBuilder;
import com.vlin.api.client.ApiClient;
import com.vlin.api.client.Method;
import com.vlin.api.client.Params;
import com.vlin.api.client.request.RequestProducer;
import com.vlin.api.client.request.defaut.DefaultedRequestProducer;
import com.vlin.api.client.response.ResponseHandler;
import com.vlin.api.client.response.defaut.DefaultResponseHandler;
import com.vlin.constant.API;

public class DefaultApiPoolClient implements ApiClient  {
			
	private List<CloseableHttpClient> list = new ArrayList<>();
	
	private String host;
	
	private API api;
	
	private Random r = new Random();
	
	private RequestProducer requestProducer = new DefaultedRequestProducer();
	
	private ResponseHandler responseHandler = new DefaultResponseHandler();
	
	public DefaultApiPoolClient() {
		this(3);
	}
	
	public DefaultApiPoolClient(int clientNum) {
		if(clientNum <= 2) {
			clientNum = 3;
		}
		for(int i = 0; i < clientNum; i ++) {
			list.add(HttpClientBuilder.builderDefaultClient());
		}
	}

	@Override
	public void setHost(String host) {
		this.host = host;
		
	}

	@Override
	public JSONObject send(String uri, Params params, Method method) {
		HttpUriRequest request = requestProducer.produceRequest(host + uri, method, params);
		try {
			int num = list.size();
			int v = r.nextInt(num);
			CloseableHttpResponse response = list.get(v).execute(request);
			System.out.println(v + " send api request");
			HttpEntity responseEntity = response.getEntity();
			String result = EntityUtils.toString(responseEntity);
			return responseHandler.handleResponse(result);
		} catch (Exception e) {
			
		}
		return null;
	}

	@Override
	public String getHost() {
		
		return this.host;
	}

	@Override
	public void setAPI(API api) {
		if(api != null) {
			this.api = api;
		}
		
	}

	@Override
	public API getAPI() {
		
		return this.api;
	}

}
